package com.warmheart.base.config;

import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.warmheart.base.interceptor.AuthInterceptor;
import com.warmheart.base.interceptor.DuplicateSubmitInterceptor;

/**
 * 
 * @ClassName: MyWebAppConfigurer
 * @Description: WEB配置
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
@Configuration
@AutoConfigureAfter({ SysConfig.class })
public class MyWebAppConfigurer implements WebMvcConfigurer {

    @Autowired
    private SysConfig sysConfig;

    /**
     * 
     * @Title: authInterceptor
     * @Description: 认证拦截器
     * @author ZhangJianyang
     * @return
     */
    @Bean
    public AuthInterceptor authInterceptor() {
        return new AuthInterceptor();
    }

    /**
     * 
     * @Title: duplicateSubmitInterceptor
     * @Description: 重复点击拦截器
     * @author ZhangJianyang
     * @return
     */
    @Bean
    public DuplicateSubmitInterceptor duplicateSubmitInterceptor() {
        return new DuplicateSubmitInterceptor() {

            @Override
            public Integer duplicateOnclickTime() {
                return sysConfig.getDuplicateOnclickTime();
            }
        };
    }


    /**
     * 配置拦截器链
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor());
        registry.addInterceptor(duplicateSubmitInterceptor());
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    /**
     * 配置信息转换
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 加入自定义的日期转换器，进行全局日期格式化
        converters.add(jackson2HttpMessageConverter());
    }

    /**
     * 
     * @Title: jackson2HttpMessageConverter
     * @Description: 自定义日期转换器
     * @author ZhangJianyang
     * @return
     */
    @Bean
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converter.setObjectMapper(mapper);
        return converter;
    }
}
